package com.mentaleye.biz;

import com.mentaleye.enums.CommonStatus;
import com.mentaleye.util.CommonPage;
import com.mentaleye.util.CommonResult;
import com.mentaleye.util.ContextUtil;
import com.mentaleye.util.ObjectUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.binding.MapperProxy;
import org.apache.log4j.Logger;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 *
 */
public class CommonBizImpl  {
    private static Logger logger = Logger.getLogger(CommonBizImpl.class);
    public static  Object  getBeanById(String  beanName,String idFiledName,Integer id){
        return getBeanById(beanName,idFiledName,id,false);
    }
//selectByExampleWithBLOBs
    public static  Object  getBeanById(String  beanName,String idFiledName,Integer id,boolean isWithBLOBs){
        Object obj=null;
        try {
            String menthodName;
            if(isWithBLOBs){
                menthodName="selectByExampleWithBLOBs";
            }else {
                menthodName="selectByExample";
            }
            Object handle= getMapperHandle(beanName);
            Object mapper=getMapper(handle);
            Object example=Class.forName("com.mentaleye.dal.model."+beanName+"Example").newInstance();
            Method createCriteria=example.getClass().getDeclaredMethod("createCriteria");
            Object criteria= createCriteria.invoke(example);
            Method queryMethod=criteria.getClass().getSuperclass().getDeclaredMethod("and"+ObjectUtil.getBig(idFiledName)+"EqualTo",Integer.class);
            queryMethod.invoke(criteria,id);
            Method selectByExample=((Class)mapper).getDeclaredMethod(menthodName,example.getClass());
            List  data=  (List) handleInvoke(beanName,handle,selectByExample,example);
            if (data!=null&&data.size()>0)
                return  data.get(0);
        }catch (Exception e){
            logger.error("查询异常",e);
        }

        return  obj;
    }



    /**
     *
     * @param bean      页面提交的对象
     * @param beanName 数据库mybatis实体对象名称
     * @param idFiledName  id字段
     * @return
     */
    public static CommonResult    edit(Object bean,String  beanName,String idFiledName,String statusFiledName){
        CommonResult commonResult=new CommonResult();
        //com.mentaleye.dal.model
        try {
            Class target=Class.forName("com.mentaleye.dal.model."+beanName);
          Object data= null;//CurriculumBean 转换成 Curriculum

            //获取传入的对象的id 属性
            Method getMethod= ObjectUtil.getFiledGetMethod(bean.getClass(),idFiledName);
          Object  idFiled=  getMethod.invoke(bean);
            Object handle= getMapperHandle(beanName);
            Object mapper=getMapper(handle);
            Method edit=null;
            try{
                data=  ObjectUtil.transfer(bean,target);//CurriculumBean 转换成 Curriculum
                if(idFiled==null){
                    //curriculumMapper.insertSelective
                    edit=((Class)mapper).getDeclaredMethod("insertSelective",data.getClass());
                    changeStatus(data,statusFiledName,CommonStatus.DEFAULT);
                }else{
                    //curriculumMapper.updateByPrimaryKeySelective
                    edit=((Class)mapper).getDeclaredMethod("updateByPrimaryKeySelective",data.getClass());
                }


            }catch (Exception e){
                target=Class.forName("com.mentaleye.dal.model."+beanName+"WithBLOBs");
                if(edit==null){
                    data=  ObjectUtil.transfer(bean,target);//CurriculumBean 转换成 Curriculum
                    if(idFiled==null){
                        //curriculumMapper.insertSelective
                        edit=((Class)mapper).getDeclaredMethod("insertSelective",data.getClass());
                        changeStatus(data,statusFiledName,CommonStatus.DEFAULT);
                    }else{
                        //curriculumMapper.updateByPrimaryKeySelective
                        edit=((Class)mapper).getDeclaredMethod("updateByPrimaryKeySelective",data.getClass());
                    }
                }
            }

            int rows=(Integer) handleInvoke(beanName,handle,edit,data);
                    //(Integer)  edit.invoke(mapper,data);
            commonResult.setIsSuccess( rows>0);

        }catch (Exception e){
            logger.error("添加修改异常",e);
        }
        return  commonResult;
    }

    private  static void changeStatus ( Object record,String statusFiledName,CommonStatus status) throws Exception{
   //修改状态
        Method statusSet=null;
        try{
            if(StringUtils.isNotEmpty(statusFiledName)){
                statusSet=record.getClass().getDeclaredMethod("set"+ObjectUtil.getBig(statusFiledName),Integer.class);
                statusSet.invoke(record, status.getCode());
            }
        }catch (Exception e){
            if(statusSet==null){
                statusSet=record.getClass().getSuperclass().getDeclaredMethod("set"+ObjectUtil.getBig(statusFiledName),Integer.class);
                statusSet.invoke(record, status.getCode());
            }

        }

    }

    /**
     *
     * @param beanName  数据库mybatis实体对象名称
     * @param commonPage
     */
    public static void   queryByPage(String  beanName,CommonPage commonPage) {
        try {
            Object handle= getMapperHandle(beanName);
            Object mapper=getMapper(handle);
            List<Map<String, Object>> result;
            Method selectMap=((Class)mapper).getDeclaredMethod("selectByMap",Map.class);
            result=( List<Map<String, Object>>) handleInvoke(beanName,handle,selectMap,commonPage.pageToMap());
            Class target=Class.forName("com.mentaleye.bean."+beanName+"Bean");
            commonPage.setPageData( ObjectUtil.transferListMap(result,target));
        }catch (Exception e){
            logger.error("分页查询异常",e);
        }

    }
    /**
     *
     * @param beanName  返回查询的列表
     * @param paramsMap
     */
    public static  List<Object>    queryByMap(String  beanName,Map<String, Object> paramsMap) {
        List<Object> result=null;
        try {
            Object handle= getMapperHandle(beanName);
            Object mapper=getMapper(handle);
            Method selectMap=((Class)mapper).getDeclaredMethod("selectByMap",Map.class);
            Class target=Class.forName("com.mentaleye.bean."+beanName+"Bean");
            result=( ObjectUtil.transferListMap(( List<Map<String, Object>>) handleInvoke(beanName,handle,selectMap,paramsMap),target));
        }catch (Exception e){
            logger.error("分页查询异常",e);
        }
        return result;

    }

    //Map<String, Object> paramsMap = JSONObject.parseObject(params);


    /**
     *
     * @param beanName 数据库mybatis实体对象名称
     * @param ids      传入要删除的id
     * @param idFiledName  id的字段名
     * @param statusFiledName  状态字段名  当为null时候就直接删除记录 不为null就修改状态为删除状态
     * @return
     */
    public static CommonResult   delete(String  beanName, List<Integer> ids,String idFiledName,String statusFiledName){
        CommonResult commonResult=new CommonResult();
        try {
            Object handle= getMapperHandle(beanName);
            Object mapper=getMapper(handle);
            Object example=Class.forName("com.mentaleye.dal.model."+beanName+"Example").newInstance();
            Method createCriteria=example.getClass().getDeclaredMethod("createCriteria");
            Object criteria= createCriteria.invoke(example);

            Method queryMethod=criteria.getClass().getSuperclass().getDeclaredMethod("and"+ObjectUtil.getBig(idFiledName)+"In",List.class);
            queryMethod.invoke(criteria,ids);
            int rows ;
            if(StringUtils.isEmpty(statusFiledName)){ //直接删除
                Method delete=((Class)mapper).getDeclaredMethod("deleteByExample",example.getClass());
                rows=  (Integer) handleInvoke(beanName,handle,delete,example);
            }else{//修改状态为删除状态
                Object record=Class.forName("com.mentaleye.dal.model."+beanName).newInstance();
                changeStatus(record,statusFiledName,CommonStatus.DELETE);
                Method update=null;
                try{
                    update=((Class)mapper).getDeclaredMethod("updateByExampleSelective",record.getClass(),example.getClass());
                }catch (Exception e){
                }
                if(update==null){
                    record=Class.forName("com.mentaleye.dal.model."+beanName+"WithBLOBs").newInstance();
                    changeStatus(record,statusFiledName,CommonStatus.DELETE);
                    update=((Class)mapper).getDeclaredMethod("updateByExampleSelective",record.getClass(),example.getClass());
                }
                rows=(Integer) handleInvoke(beanName,handle,update,record,example);

            }
            commonResult.setIsSuccess(rows == ids.size());
        }catch (Exception e){
            logger.error("批量删除异常",e);
        }
        return  commonResult;
    }
   //获取mapperhandle
    public static Object getMapperHandle(String beanName) throws Exception{
        //mapperInterface
        Object  proxy=ContextUtil.getBean(Class.forName("com.mentaleye.dal.service."+beanName+"Mapper"));
        Field h =proxy.getClass().getSuperclass().getDeclaredField("h");
        h.setAccessible(true);
        return h.get(proxy);
    }
   //获取mapper接口类型
    public static Object getMapper(Object handle) throws Exception{
        Field field =MapperProxy.class.getDeclaredField("mapperInterface");
        field.setAccessible(true);
        return   field.get(handle);
    }
   //handle执行invoke方法
    public static Object handleInvoke(String beanName,Object handle, Method method, Object... args) throws Exception{
        Method invoke =InvocationHandler.class.getDeclaredMethods()[0];
        invoke.setAccessible(true);
        Object  proxy=ContextUtil.getBean(Class.forName("com.mentaleye.dal.service."+beanName+"Mapper"));
        return   invoke.invoke(handle,proxy,method,args);
    }

}
